<template>
  <article class="media">
    <div class="media-content">
      <form @submit.prevent="onSubmit">
        <b-field>
          <b-input
            v-model.lazy="commentText"
            type="textarea"
            maxlength="400"
            :placeholder="$t('comment.placeholder')"
            :disabled="isLoading"
          ></b-input>
        </b-field>
        <nav class="level">
          <div class="level-left">
            <b-button
              type="is-primary"
              native-type="submit"
              class="level-item"
              :disabled="isLoading"
            >
              {{ $t("comment.submit") }}
            </b-button>
          </div>
        </nav>
      </form>
    </div>
  </article>
</template>

<script>
import { pushComment } from "@/api/comment";

export default {
  name: "CommentForm",
  data() {
    return {
      commentText: "",
      isLoading: false,
    };
  },
  props: {
    slug: {
      type: String,
      default: null,
    },
  },
  methods: {
    async pushComment() {
      pushComment(commentText).then((response) => {
        const { data } = response;
        this.commentText = "";
      });
    },

    async onSubmit() {
      this.isLoading = true;
      try {
        let postData = {};
        if (this.commentText.trim().length != 0) {
          postData["content"] = this.commentText;
          postData["topic_id"] = this.slug;
          await pushComment(postData);
          this.$emit("loadComment", this.slug);
          this.$message.success(this.$t("comment.success"));
          this.commentText = "";
        } else {
          this.$message.error(this.$t("comment.empty"));
        }
      } catch (e) {
        this.$message.error(this.$t("comment.failed", [e]));
      } finally {
        this.isLoading = false;
      }
    },
  },
};
</script>